package com.topnav.mc.api;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.js.lib.annotation.ApiLogger;
import com.js.lib.result.Result;
import com.js.lib.utils.JsonUtil;
import com.topnav.mc.admin.entity.Device;
import com.topnav.mc.admin.entity.Site;
import com.topnav.mc.admin.entity.User;
import com.topnav.mc.admin.service.IDeviceService;
import com.topnav.mc.admin.service.ISiteService;
import com.topnav.mc.admin.service.IUserService;
import com.topnav.mc.admin.utils.SystemLogUtil;
import com.topnav.mc.document.bean.DocumentParam;
import com.topnav.mc.document.entity.Document;
import com.topnav.mc.document.service.IDocumentService;
import com.topnav.mc.exception.DocWriteFromSiteRuntimeException;
import com.topnav.mc.exception.ExceptionMsg;
import com.topnav.mc.uitls.ErrorResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("api")
@Slf4j
public class DocumentApiController {
    @Autowired
    private SystemLogUtil systemLogUtil;
    @Autowired
    private ISiteService siteService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IDeviceService deviceService;
    @Autowired
    private IDocumentService documentService;
    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 文件信息上报,采集站，存储，终端设备文件登记
     *
     * @param param
     * @return
     */

    @ApiLogger(apiName="api/document/write")
    @PostMapping("/document/write")
    @ResponseBody
    public Result download(@RequestBody @Validated DocumentParam param, HttpServletRequest request, HttpServletResponse response) {
        String fileName = "空的文件名";
        try {
            fileName = param.getDocName();
            if (StringUtils.isEmpty(param.getSiteCode())) {
                throw new DocWriteFromSiteRuntimeException(fileName, 1, String.format("采集站编号{%s}为空", param.getSiteCode()));
            }
            if (StringUtils.isEmpty(param.getDeviceCode())) {
                systemLogUtil.saveLog(1, fileName, 2, String.format("设备号{%s}为空", param.getDeviceCode()));
            }
            if (StringUtils.isEmpty(param.getUserCode())) {
                systemLogUtil.saveLog(1, fileName, 2, String.format("人员编号{%s}为空", param.getUserCode()));
            }
            Document doc = new Document();
            param.assignTo(doc);
            /** 采集站 */
            if (!StringUtils.isEmpty(param.getSiteCode())) {
                QueryWrapper<Site> wrapper = new QueryWrapper<>();
                wrapper.eq("code", param.getSiteCode());
                Site site = siteService.getOne(wrapper, false);
                if (site == null) {
                    throw new DocWriteFromSiteRuntimeException(fileName, 1, String.format("采集站编号{%s}没有注册", param.getSiteCode()));
                }else{
                    doc.setSiteId(site.getId());
                }
            }
            /** 用户 */
            if (!StringUtils.isEmpty(param.getUserCode())) {
                QueryWrapper<User> wrapper = new QueryWrapper<>();
                wrapper.eq("code", param.getUserCode());
                User user = userService.getOne(wrapper, false);
                if (user == null) {
                    systemLogUtil.saveLog(1, fileName, 2, String.format("用户编号{%s}没有注册", param.getUserCode()));
                    //throw new DocWriteFromSiteRuntimeException(fileName,1,String.format("用户编号{%s}没有注册",param.getUserCode()));
                }else {
                    doc.setUserId(user.getId());
                    doc.setOrgId(user.getOrgId());
                }
            }
            /** 设备 */
            if (!StringUtils.isEmpty(param.getDeviceCode())) {
                QueryWrapper<Device> wrapper = new QueryWrapper<>();
                wrapper.eq("code", param.getDeviceCode());
                Device device = deviceService.getOne(wrapper, false);
                if (device == null) {
                    throw new DocWriteFromSiteRuntimeException(fileName, 1, String.format("设备号{%s}没有注册", param.getDeviceCode()));
                }else{
                    doc.setDeviceId(device.getId());
                }
            }
            doc.setCreateTime(new Date());
            doc.setUploadTime(new Date());
            doc.setUpdateTime(new Date());
            documentService.save(doc);
            systemLogUtil.saveLog(1, fileName, 3, String.format("文件{%s}上报成功", fileName));
            return Result.ok();
        } catch (DocWriteFromSiteRuntimeException e) {
            throw e;
        } catch (Exception e1) {
            /** e1.getMessage() 会得到 null值*/
            throw new DocWriteFromSiteRuntimeException(fileName, 1, e1.toString());
        }
        /*Page datas = documentService.searchDocument(p.getPage(),p.getWhere());*/
        //return Result.ok();
    }

    /**
     * 采集测试连接
     * 根据用户名，密码，IP,PORT查询采集站，并返回采集站编号
     *
     * @param username
     * @param password
     * @param host
     * @param port
     * @return
     */
    @GetMapping("/site/check")
    @ResponseBody
    public Result formSiteCheck(String username, String password, String host, Integer port) {
        QueryWrapper<User> uWrapper = new QueryWrapper();
        uWrapper.eq("login_name", username);
        User user = userService.getOne(uWrapper, false);
        if (user == null) {
            /** 不存在的用户 */
            return ErrorResultUtil.result(ExceptionMsg.ERROR_AUTHENTICATION_NOT_EXISTS_USER, username);
        }
        if (!passwordEncoder.matches(password, user.getPassword())) {
            /** 密码错误 */
            return ErrorResultUtil.result(ExceptionMsg.ERROR_AUTHENTICATION_PASSWORD_FAILE);
        }

        if (!user.getEnabled()) {
            /** 用户 [%s] 已被禁止！ */
            return ErrorResultUtil.result(ExceptionMsg.ERROR_AUTHENTICATION_ENABLED_FAILE, username);
        }

        QueryWrapper<Site> sWrapper = new QueryWrapper();
        sWrapper.eq("host", host);
        sWrapper.eq("port", port);
        Site site = siteService.getOne(sWrapper, false);

        if (site == null) {
            /** 设备 [%s] 未注册！ */
            return ErrorResultUtil.result(ExceptionMsg.ERROR_NOT_EXISTS_SITE_EXCEPTION, port == null ? host : host + ":" + port.toString());
        }

        return Result.ok(site);
    }

    @PostMapping("/site/keepalive")
    @ResponseBody
    public Result siteKeepalive(@RequestBody Map<String, Object> param, HttpServletRequest request) {
        log.debug(JsonUtil.toJson(param));
        return Result.ok();
    }
}
